package com.cloudfun.campusshare.schedule;

import com.cloudfun.campusshare.common.constant.PayPlatform;
import com.cloudfun.campusshare.common.model.dto.RefundSettlementDto;
import com.cloudfun.campusshare.entity.DailyBalanceAccountEntity;
import com.cloudfun.campusshare.repo.DailyBalanceAccountEntityRepo;
import com.cloudfun.campusshare.repo.OrderEntityRepo;
import com.cloudfun.campusshare.repo.UserEntityRepo;
import com.cloudfun.campusshare.service.OrderRefundService;
import com.cloudfun.campusshare.util.OrderNoGenUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @author : zhangyongjie
 * @version : 1.0
 * @createTime : 2020/6/1 16:08
 * @description : 运营商单日金额结算
 */
@Slf4j
@Component
public class PerDayBalanceAccountSchedule extends BaseScheduleTask {
    @Resource
    OrderEntityRepo orderEntityRepo;
    @Resource
    UserEntityRepo userEntityRepo;
    @Resource
    private DailyBalanceAccountEntityRepo dailyBalanceAccountEntityRepo;
    @Autowired
    private OrderNoGenUtil orderNoGenUtil;

    @Autowired
    private OrderRefundService orderRefundService;

    @Scheduled(cron = "0 00 16 * * ?")
    public void doBalanceAccount() {
        this.execute();
    }

    @Override
    protected String getTaskName() {
        return "单日结算";
    }

    @Override
    protected void doExecute() {
        //获取前一天
        LocalDate now = LocalDate.now();
        log.info("当前的日期为:{}", now);
        LocalDate lastDay = now.minusDays(1);
        log.info("上一天的日期为:{}", lastDay);
        List<Map> list = orderEntityRepo.balanceAmountPerDay(lastDay.toString());
        List<RefundSettlementDto> refundSettlementDtos = orderRefundService.refundSettlementStatistics(lastDay.toString());
        log.info("前一天账单分析获取结果:{}", list);
        List<String> allMerchant = userEntityRepo.findAllMerchant();
        if (list.size() > 0) {
            List<DailyBalanceAccountEntity> exists = list.stream().map(x -> {
                DailyBalanceAccountEntity dailyBalanceAccountEntity = new DailyBalanceAccountEntity();
                dailyBalanceAccountEntity.setMerchantId((String) x.get("merchantId"));
                dailyBalanceAccountEntity.setBalanceAccountNo(orderNoGenUtil.next4Advance("dr-", "DR_SUFFIX"));
                dailyBalanceAccountEntity.setJournalAmount(((BigDecimal) x.get("journalAmount")).intValue());
                dailyBalanceAccountEntity.setDiscountPrice(((BigDecimal) x.get("discountPrice")).intValue());
//                dailyBalanceAccountEntity.setHandingFee(((BigDecimal) x.get("handingFee")).intValue());
                dailyBalanceAccountEntity.setSettlementAmount(((BigDecimal) x.get("settlementAmount")).intValue());
                if (!Objects.isNull(x.get("payPlatform"))) {
                    dailyBalanceAccountEntity.setPayPlatform(PayPlatform.valueOf(x.get("payPlatform").toString()));
                } else {
                    dailyBalanceAccountEntity.setPayPlatform(PayPlatform.WX_PAY);
                }
                Optional<RefundSettlementDto> refundSettlementDto = refundSettlementDtos.stream().filter(dto ->
                        dto.getMerchantId().equals((String) x.get("merchantId")) && dto.getPayPlatform().equals(dailyBalanceAccountEntity.getPayPlatform().name()))
                        .findAny();
                /**
                 * 退款金额处理
                 */
                if (refundSettlementDto.isPresent()) {
                    dailyBalanceAccountEntity.setSettlementAmount(dailyBalanceAccountEntity.getSettlementAmount() - refundSettlementDto.get().getPrice());
                }
                dailyBalanceAccountEntity.setBillDate(lastDay);
                return dailyBalanceAccountEntity;
            }).collect(Collectors.toList());
            dailyBalanceAccountEntityRepo.saveAll(exists);
        }

        List<DailyBalanceAccountEntity> collect = allMerchant.stream().filter(x -> !list.stream()
                .map(x1 -> (String) x1.get("merchantId")).collect(Collectors.toList()).contains(x)
        ).map(x -> handleEmpty(x, lastDay)).collect(Collectors.toList());
        dailyBalanceAccountEntityRepo.saveAll(collect);
    }

    private DailyBalanceAccountEntity handleEmpty(String merchantId, LocalDate date) {
        DailyBalanceAccountEntity dailyBalanceAccountEntity = new DailyBalanceAccountEntity();
        dailyBalanceAccountEntity.setBillDate(date);
        dailyBalanceAccountEntity.setBalanceAccountNo(orderNoGenUtil.next4Advance("dr-", "DR_SUFFIX"));
        dailyBalanceAccountEntity.setMerchantId(merchantId);
        dailyBalanceAccountEntity.setJournalAmount(0);
        dailyBalanceAccountEntity.setDiscountPrice(0);
        dailyBalanceAccountEntity.setHandingFee(0);
        dailyBalanceAccountEntity.setSettlementAmount(0);
        return dailyBalanceAccountEntity;
    }

    public static void main(String[] args) {
        System.out.println(LocalDate.now().toString());
    }

}
